package com.ctlele.team.space.activity.impl;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.ctlele.team.space.R;
import com.ctlele.team.space.util.InputStreamUtils;
import com.ctlele.team.space.widget.view.PageHeader;
import com.github.barteksc.pdfviewer.PDFView;

import java.io.InputStream;

public class PdfViewActivity extends AppCompatActivity {

    private static final String TAG = "PdfViewActivity";

    public static final String URL_KEY = "url";

    public static final String TITLE_KEY = "title";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pdf_view);

        String url = getIntent().getStringExtra(URL_KEY);
        String title = getIntent().getStringExtra(TITLE_KEY);

        if (TextUtils.isEmpty(url) || !url.startsWith("http")) onBackPressed();

        PageHeader header = findViewById(R.id.page_header);
        PDFView pdfView = findViewById(R.id.pdf_view);
        TextView titleView = header.findViewById(R.id.title);

        if (!TextUtils.isEmpty(title)) {
            titleView.setText(title);
        }

        ImageView back = header.findViewById(R.id.go_back);
        back.setOnClickListener((view) -> onBackPressed());

        Log.i(TAG, url);

        new Thread(() -> {
            try (InputStream inputStream = InputStreamUtils.openHttpStream(url)) {
                byte[] pdf = InputStreamUtils.readStream(inputStream);
                pdfView.fromBytes(pdf).load();
            } catch (Exception e) {
                Log.e(TAG, e.getMessage(), e);
            }
        }).start();
    }
}